<template>
  <a-select
      show-search
      allowClear
      :label-in-value="typeof value !== 'string'"
      :value="value"
      placeholder="Select users"
      style="width: 100%"
      :filter-option="false"
      :not-found-content="fetching ? undefined : null"
      @search="fetchUser"
      @change="handleChange">
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-for="(d, index) in data" :key="index" :value="d.mobile" :label="d.realName">
      {{ d.realName }}
    </a-select-option>
  </a-select>
</template>

<script>
import debounce from 'lodash/debounce';
import { selectUserList } from '@/api/api'

export default {
  name: 'select-query',
  props: {
    value: {
      required: true,
    },
    options: {
      type: Array,
      required: true,
      default: []
    },
  },
  data () {
    this.lastFetchId = 0;
    this.fetchUser = debounce(this.fetchUser, 800);
    return {
      data: this.options,
      fetching: false,
    };
  },
  watch: {
    options(value) {
      this.data = value
    }
  },
  methods: {
    fetchUser (value) {
      console.log('fetching user', value);
      this.lastFetchId += 1;
      const fetchId = this.lastFetchId;
      this.data = [];
      // this.$emit('updateOptions', [])
      // this.$emit('update.options', [])
      this.fetching = true;
      selectUserList({ realName: value }).then(res => {
        if (res.success) {
          if (fetchId !== this.lastFetchId) {
            // for fetch callback order
            return;
          }
          // this.$emit('updateOptions', res.result)
          // this.$emit('update.options', res.result)
          this.data = res.result
        }
        this.fetching = false;
        console.log('this.fetching', this.fetching)
        console.log('this.data', this.data)
      })
    },
    handleChange (value) {
      this.$emit('change', value)
    },
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>
